package cn.rengy.web.framework.sys.login.web;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.lang.ResultEntity;
import cn.rengy.web.framework.constants.Constants;
import cn.rengy.web.framework.jwt.JwtService;
import cn.rengy.web.framework.principal.Identity;
import cn.rengy.web.framework.property.service.PropertyService;
import cn.rengy.web.framework.securitycode.SecurityCodeService;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.util.GetSessionUtils;
import cn.rengy.web.framework.wxmp.message.TemplateMessageService;
import cn.rengy.web.framework.wxmp.message.WxMsgTemplateInstanceId;
import cn.rengy.web.framework.wxmp.message.entity.TemplateMessage;

@Service
public class SysLoginService {
	@Autowired
	private DbService dbService;
	@Autowired
	private PropertyService propertyService;
	@Autowired
	private TemplateMessageService templateMessageService;
	@Autowired
	private SecurityCodeService securityCodeService;
	 
	public Map<String,Object> getUserInfo(){
		Long userid=GetSessionUtils.getUserId();
		return this.dbService.queryForMap("select_get_user_info", userid);
		//return getUserInfo(userid);
	}
	/**
	 * 发送微信登录验证码
	 * @param username
	 * @return
	 */
	public ResultEntity<?> sendSecurityCode(Map<String,Object> paramMap){
		String appid=propertyService.getProperty(Constants.KEY_WxmpAppid);
		String username=MapUtils.getString(paramMap,"username");
		//1.校验用户名是否存在
		String openid=this.dbService.querySingleColumn("select_get_openid_by_username", String.class, username,appid);
		if(StringUtils.isBlank(openid)){
			return ResultEntity.fail("用户名不存在");
		}
		//2.保存验证码
		ResultEntity<String> r=securityCodeService.save(Constants.KEY_WXSECURITYCODELOGIN, username);
		if(!r.isSuccess()) {
			return r;
		}
		String code=r.getData();//验证码
		//3.发送模板消息
		Map<String,String> dataMap=new HashMap<String,String>(1,1);
		dataMap.put("code", code);
		TemplateMessage templateMessage=new TemplateMessage();
		templateMessage.setAppid(appid);
		templateMessage.setData(dataMap);
		List<String> openidList=new ArrayList<String>(1);
		openidList.add(openid);
		templateMessage.setOpenidList(openidList);
		templateMessage.setTemplate_instance_id(WxMsgTemplateInstanceId.YZM);
		templateMessage.setUrl(null);
		try {
			templateMessageService.sendTemplateMessage(templateMessage);
		}catch(Exception e) {
			securityCodeService.evict(Constants.KEY_WXSECURITYCODELOGIN, username);
			return ResultEntity.fail("发送失败");
		}
		return ResultEntity.ok();
	}
	
	public void login(AuthenticationToken token) {
		Subject subject = SecurityUtils.getSubject();
    	subject.login(token);
		onLoginSuccess(token,subject);
	}
	public void refreshToken(String refresh_token) {
		Identity identity=JwtService.parseToken(refresh_token);
		//String userId=identity.getName();
		//是否需要查询数据？
		//String access_token=JwtService.createToken(identity, Duration.ofMinutes(1));
		String access_token=JwtService.createToken(identity, Duration.ofHours(3));
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
	    HttpServletResponse response = servletRequestAttributes.getResponse();
	    JSONObject jo=new JSONObject();
	    jo.put("access_token", access_token);
	    response.setHeader(HttpHeaders.AUTHORIZATION,jo.toString());
	    
	}
	private void onLoginSuccess(AuthenticationToken token,Subject subject) {
		Identity identity=(Identity)subject.getPrincipal();
		//登录成功后创建token和refreshToken
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
	    //HttpServletRequest request = servletRequestAttributes.getRequest();
	    HttpServletResponse response = servletRequestAttributes.getResponse();
	    //String access_token=JwtService.createToken(identity,Duration.ofMinutes(1));
	    //String refresh_token=JwtService.createToken(identity,Duration.ofMinutes(5));
	    String access_token=JwtService.createToken(identity,Duration.ofHours(1));
	    String refresh_token=JwtService.createToken(identity,Duration.ofDays(31));
	    JSONObject jo=new JSONObject();
	    jo.put("access_token", access_token);
	    jo.put("refresh_token", refresh_token);
	    response.setHeader(HttpHeaders.AUTHORIZATION,jo.toString());
	}
}
